import React, {useState, useCallback, useEffect} from 'react';
import {Select} from 'antd';
import {fetchOptions} from '~/service/liveMonitor';

import {dimensionMap} from '../../config.js';
import {useMount, useDebounceFn} from 'ahooks';

const {Option} = Select;

// 参数格式化
const generateParams = (id, searchKey) => ({
    dimensionId: id,
    dimensionName: dimensionMap.get(id).dimensionName,
    searchKey,
    unitId: dimensionMap.get(id).unitId,
    unitName: dimensionMap.get(id).unitId,
    pager: {pageSize: 200, pageNum: 1},
    permissions: []
});

export default ({
    selectName,
    value,
    onChange,
    setValue,
}) => {

    const [options, setOptions] = useState([]);

    const getOptions = useCallback(async (selectName, searchKey) => {
        const finalParams = generateParams(selectName, searchKey);
        const res = await fetchOptions(finalParams);
        if (res?.code === 0 && res?.data) {
            setOptions(['全部'].concat(res?.data || []));
        }
    }, []);

    useMount(() => {
        getOptions(selectName, '');
    });

    const handleSearch = value => {
        getOptions(selectName, value);
    };
    const {run: handleDebounceSearch} = useDebounceFn(value => {
        handleSearch(value);
    }, {wait: 500});

    const handleChange = value => {
        typeof onChange === 'function' ? onChange(value) : setValue(value);
    };
    const handleClear = () => {
        getOptions(selectName, '');
    };

    return (
        <Select
            value={value}
            showSearch
            onSearch={handleDebounceSearch}
            onChange={handleChange}
            getPopupContainer={node => node.parentNode}
            filterOption={false}
            onClear={handleClear}
        >
            {
                options?.map(item => (
                    <Option key={item} value={item} title={item}>
                        {item}
                    </Option>
                ))
            }
        </Select>
    );
};
